import { useState } from 'react';
import useMountData from './useMountData';

/**
 *
 * @param form  antd form表单
 * @param service 请求接口方法
 * @param cb  接口请求完成后 结果回调
 * @param unmount 页面卸载执行方法
 * @returns {handleSubmit} 事件触发方法
 */
const useFormSubmit = (form, service, cb, unmount) => {
  const { validateFieldsAndScroll, resetFields } = form;
  const [submit, setSubmit] = useState({ waitRun: true });
  const successCb = () => {
    resetFields();
  };

  const result = useMountData(service, [submit], cb, undefined, unmount);
  if (!submit.waitRun && result !== undefined) {
    // cb && cb(result);
    // 默认提交成功后重置表单
    !cb && !!result && successCb();
    setSubmit({ waitRun: true });
  }

  const handleSubmit = params => e => {
    e && e.preventDefault();
    e && e.stopPropagation();

    validateFieldsAndScroll(async (err, v) => {
      if (!err) {
        setSubmit({
          ...params,
          ...v,
          waitRun: false,
        });
      }
    });
  };

  return handleSubmit;
};

export default useFormSubmit;
